/**
 * Created by MetaLab_Gu on 2016/4/28.
 */
'use script';
angular.module('metalabPartnerApp').controller('ProjectCtrl', ['$rootScope', '$scope', '$stateParams', 'MetaResources', '$state', 'MetaSEO', 'MetaRemind', '$q',
    function ($rootScope, $scope, $stateParams, resource, $state, MetaSEO, MetaRemind, $q) {

        MetaSEO.setSEO('我的项目', '迈科技项目', '负责项目,合作项目,关联项目');

        $scope.waiting = true;//加载中标志

        ///--载入数据
        $scope.datas = {
            'charge': [],
            'inCharge': 0,
            'cooperate': [],
            'inCooperate': 0,
            'relate': [],
            'inRelate': 0,
        };

        /**
         * 开通人才
         * @author Yud
         */
        $scope.openTalent = function () {
            resource.talent.open({'userId': '_self'}, {}, function (data) {
                MetaRemind.success('开通成功');
                $rootScope.USER.talentOpened = true;
                $state.go('meta.talent.edit');
            }, function (error) {
                MetaRemind.error(error);
            });
        };

        /**
         * @function 判断进程所属的项目是否属于某个项目存储列表
         * @param target 进程所属的项目id
         * @param projects 某个项目存储列表
         * @returns {*} -1:不存在，number>-1:存在的索引位置，false:项目存储列表无效
         */
        var hasProject = function (target, projects) {
            for (var index in projects) {
                if (projects[index].id === target) {
                    return index;//项目列表中已存在当前进程所属的项目
                }
            }
            return -1;//不存在
        };

        /**
         * @function 将项目添加到项目列表
         * @param data 进程数据
         * @param storage 具体某类型的项目存储列表
         * @returns {boolean} false：无效进程
         */
        var getProject = function (j, storage) {
            var index = hasProject(temp_datas[j].projectId, storage);
            var deferred = $q.defer();
            resource.note.get({
                userId: '_self',
                solutionProcessId: temp_datas[j].id,
                _sort: '-updatedAt'
            }, function (remarks) {
                temp_datas[j].remarks = remarks;
                if (index !== -1) {//已经存在相同的项目
                    storage[index].processes.push(angular.copy(temp_datas[j]));
                } else {//不存在相同的项目
                    temp_datas[j].project.processes = [];
                    temp_datas[j].project.processes.push(angular.copy(temp_datas[j]));
                    storage.push(angular.copy(temp_datas[j].project));
                }
                deferred.resolve('success');
            }, function (err) {
                MetaRemind.error("出错啦！", err);
                deferred.resolve('error');
            });
            return deferred.promise;
        };

        var temp_datas = [];//存放用户的进程，全局使用的数据

        /**
         * @function 递归循环规整进程项目和备注，保证每个进程一次整理完毕
         * @param i 进程索引值
         */
        var goThroughProcess = function (i) {
            var temp_userid = $scope.$root.USER.id;
            var promise;
            // console.log(i);
            // console.log(i, temp_datas[i], temp_datas[i].technology.verified);
            if (temp_datas[i].demand && temp_datas[i].technology) {
                if (temp_datas[i].demand.leaderId === temp_userid && temp_datas[i].technology.verified) {
                    promise = getProject(i, $scope.datas.charge);
                } else if (temp_datas[i].technology.leaderId === temp_userid && temp_datas[i].demand.verified) {
                    promise = getProject(i, $scope.datas.cooperate);
                } else if ((temp_datas[i].demand.publisherId === temp_userid && temp_datas[i].technology.verified) || (temp_datas[i].technology.publisherId === temp_userid && temp_datas[i].demand.verified)) {
                    promise = getProject(i, $scope.datas.relate);
                }
            }
            if (promise) {
                promise.then(function () {
                    // console.log($scope.datas);
                    // console.log(i, temp_datas.length);
                    if (i < temp_datas.length - 1) {
                        goThroughProcess(i + 1);
                    } else {
                        initTab();
                    }
                });
            } else {
                if (i < temp_datas.length - 1) {
                    goThroughProcess(i + 1);
                } else {
                    initTab();
                }
            }
        };

        /**
         * @function 初始化tabs
         */
        var initTab = function () {
            $scope.tabs = [
                {
                    name: '负责项目(' + $scope.datas.charge.length + ')',
                    active: $state.is('meta.project.list.charge'),
                    select: function () {
                        $state.go('meta.project.list.charge');
                    }
                }, {
                    name: '合作项目(' + $scope.datas.cooperate.length + ')',
                    active: $state.is('meta.project.list.cooperate'),
                    select: function () {
                        $state.go('meta.project.list.cooperate');
                    }
                }, {
                    name: '关联项目(' + $scope.datas.relate.length + ')',
                    active: $state.is('meta.project.list.relate'),
                    select: function () {
                        $state.go('meta.project.list.relate');
                    }
                }
            ];
        };

        /**
         * @function 获取进程
         */
        var getProcess = function () {
            resource.process.userProcess({
                user_id: "_self",
                _sort: '-updatedAt',
                _embed: 'demandSideProcess,technologySideProcess,Project,Demand,Technology,User,project.demand,project.demand.projectManager，project.demand.enterpriseInfo,technology.leader,demand.leader'
            }, function (datas) {
                // console.log('length', datas.length);
                if (datas.length < 1) {
                    initTab();
                    $scope.waiting = false;
                    return;
                }
                temp_datas = datas;
                goThroughProcess(0);
                $scope.waiting = false;

            }, function (error) {
                $scope.waiting = false;
                console.log('err', error);
            }).$promise.then(function () {
            });
            // console.log('final:', $scope.datas);
        }

        getProcess();
    }]);
